import requests
from bs4 import BeautifulSoup
import json
import re
from utils.req import get_request


base_url = "https://www.invivogen.com"
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "max-age=0",
    "Connection": "keep-alive",
    "Referer": "https://www.invivogen.com",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
}


def extract_js_data(text) -> str:
    template = "var jsonResults = (.*);"
    match = re.search(template, text)
    if match:
        return match.group(1)
    return None


def get_search_product(keyword) -> BeautifulSoup:

    url = "https://www.invivogen.com/search"
    params = {"sq": keyword, "st": ""}
    response = get_request(url=url, headers=headers, params=params)
    print(response.status_code)
    soup = BeautifulSoup(response.text, "html.parser")
    return soup


def extract_product_info(soup) -> str:
    """提取商品信息"""
    search_result = soup.find("div", attrs={"id": "search-results"})
    if search_result:  # 搜索结果
        script = search_result.find("script")
        if script:  # 脚本
            script_data = script.text.strip()
            json_data = extract_js_data(script_data)
            if json_data:  # 脚本数据
                url = json.loads(json_data)[0]["aData"]["url"]
                if url.startswith("/"):
                    return base_url + url
    return None


def get_prodes(url) -> BeautifulSoup:
    res = get_request(url=url, headers=headers)
    print(res.status_code)
    soup = BeautifulSoup(res.text, "html.parser")
    return soup


def extract_product_detail(soup) -> str:
    """提取商品详情"""
    product_detail = soup.find("div", attrs={"id": "about"})
    if product_detail:
        return str(product_detail)
    product_detail_hidden = soup.find("div", attrs={"class": "show-more"})
    if product_detail_hidden:
        return str(product_detail_hidden)
    return None

def process_product(procode)->str:
    if search_des := get_search_product(procode):
        if pro_url := extract_product_info(search_des):
            if pro_detail := get_prodes(pro_url):
                return extract_product_detail(pro_detail)
    return None


if __name__ == "__main__":
    res = process_product("rbd-lucia-v4")
    print(res)
